package com.peng.leetcode.dynamic;

/**
 * CoinChange
 *
 * 钱币找零问题
 *
 * 需要找 27 元， 有 2，5，7 的面额。 最少多少张能凑够 27元
 *
 * @author: lupeng6
 * @create: 2021/4/8 10:33
 */
public class CoinChange {

    public static void main(String[] args) {
        System.out.println(new CoinChange().coinChange(27, new int[]{2, 5, 7}));
    }

    /**
     * dp[x] = min(dp[x - 2] + 1, dp[x - 5] + 1, dp[x - 7] + 1)
     *
     * @author lupeng6
     * @date 2021/4/8 10:35
     */
    public int coinChange(int target, int[] coins) {
        if (target <= 0) {
            return 0;
        }

        int[] dp = new int[target + 1];
        dp[0] = 0;
        for (int i = 1; i <= target; i++) {
            dp[i] = Integer.MAX_VALUE;
            for (int j = 0; j < coins.length; j++) {
                if (i >= coins[j] && dp[i - coins[j]] != Integer.MAX_VALUE) {
                    dp[i] = Math.min(dp[i - coins[j]] + 1, dp[i]);
                }
            }
        }

        if (dp[target] == Integer.MAX_VALUE) {
            return -1;
        }
        return dp[target];
    }
}
